<?php

/*

___Canvas Installation Scripts__________________________________

Creates the necessary SQL tables for a clean Canvas install.

________________________________________________________________

*/

if(is_admin()) canvas_check_tables();

function canvas_check_tables() { 
	global $wpdb, $canvas;
	
	foreach($canvas as $table) {
		if(!$wpdb->query("SHOW TABLES LIKE '".$table."'")) {
			canvas_create_db($table);
		}
	}
	if(get_option('canvas_version') == '1.1') {
		$wpdb->query("ALTER TABLE ".$canvas->main." MODIFY ubi text NOT NULL");
		$blocks = $wpdb->get_results("SELECT block_id, block_name, type, author, uri, description, block_group, path FROM ".$canvas->main);
		if($blocks) {
			foreach($blocks as $block) {
				$hash_data = $block->block_name.$block->author.$block->uri.$block->description.$block->block_group;
				if($block->type == 'plugin') $hash_data .= $block->path;
				$ubi = md5($hash_data);
				$wpdb->query("UPDATE ".$canvas->main." SET ubi = '$ubi' WHERE block_id = '".$block->block_id."'");
			}
		}
	}

	$filename = CANVASPATH.'/canvas.php';
	$file_data = implode('', file($filename));
	preg_match("|Version:(.*)|i", $file_data, $version);
	update_option('canvas_version',$version[1]);
}

function canvas_clean_install() {
    global $wpdb, $canvas;
	$wpdb->query("DROP TABLE IF EXISTS ".$canvas->main."");
	$wpdb->query("DROP TABLE IF EXISTS ".$canvas->variables."");
	$wpdb->query("DROP TABLE IF EXISTS ".$canvas->options."");
	canvas_install();
	return true;
}

function canvas_clean_deactivate() {
    global $wpdb, $table_prefix;
	$wpdb->query("DROP TABLE IF EXISTS ".$table_prefix.'canvas'."");
	$wpdb->query("DROP TABLE IF EXISTS ".$table_prefix.'canvas_variables'."");
	$wpdb->query("DROP TABLE IF EXISTS ".$table_prefix.'canvas_var_options'."");
	return true;
}

function canvas_create_db($table = '') {
	global $wpdb, $canvas;

    require_once(ABSPATH . 'wp-admin/upgrade-functions.php');

	${$canvas->main} = "CREATE TABLE ".$canvas->main." (
	        block_id INT NOT NULL AUTO_INCREMENT,
	        PRIMARY KEY(block_id),
   			block_name text NOT NULL,
   			type tinytext NOT NULL,
   			zone tinytext NOT NULL,
   			position int(6) NOT NULL,
   			author tinytext NOT NULL,
   			description text NOT NULL,
   			block_group tinytext NOT NULL,
   			uri text NOT NULL,
   			path text NOT NULL,
   			theme tinytext NOT NULL,
   			ubi text NOT NULL
			);";

	${$canvas->variables} = "CREATE TABLE ".$canvas->variables." (
   			variable_id INT NOT NULL AUTO_INCREMENT,
   			PRIMARY KEY(variable_id),
   			variable_name text NOT NULL,
   			parent INT NOT NULL,
   			type text NOT NULL,
   			value text NOT NULL,
   			default_value text NOT NULL,
   			description text NOT NULL
			);";

	${$canvas->options} = "CREATE TABLE ".$canvas->options." (
   			option_id INT NOT NULL AUTO_INCREMENT,
   			PRIMARY KEY(option_id),
   			var_id INT NOT NULL,
   			option_text text NOT NULL,
   			option_value text NOT NULL
			);";

	${$canvas->zone_options} = "CREATE TABLE ".$canvas->zone_options." (
   			option_id INT NOT NULL AUTO_INCREMENT,
   			PRIMARY KEY(option_id),
   			zone text NOT NULL,
   			option_name text NOT NULL,
   			value text NOT NULL,
   			theme text NOT NULL
			);";

	if($table == '') {
		foreach($canvas as $table) {
			dbDelta(${$table});
		}
	} else {
		dbDelta(${$table});
	}
	return;
}

function canvas_install() {
    global $wpdb, $canvas, $installed, $canvas_external_plugins;
    if(!$wpdb->get_var("SHOW TABLES LIKE '".$canvas->main."'") == $canvas->main) canvas_create_db();
	if(file_exists(get_template_directory().'/canvas.php') && !$wpdb->get_results("SELECT block_id FROM ".$canvas->main." WHERE theme = '".get_option('template')."'")) {
		$position = 1;
		if(!empty($canvas_external_plugins)) {
			foreach($canvas_external_plugins as $file) {
				if(file_exists($file)) {
					canvas_import_plugin($file, $position);
					$position++;
				}
			}
		}
		$canvas_dir = CANVASPATH.'/plugins/';
		$theme_dir = get_template_directory().'/plugins/';
		list($plugins, $position) = canvas_import_plugins($position, $canvas_dir);
		list($plugins, $position) = canvas_import_plugins($position, $theme_dir);
		$canvas_dir = CANVASPATH.'/blocks/';
		$theme_dir = get_template_directory().'/blocks/';
		list($plugins, $position) = canvas_import_blocks($position, $canvas_dir);
		list($plugins, $position) = canvas_import_blocks($position, $theme_dir);

	} elseif(file_exists(get_template_directory().'/canvas.php')) {
		canvas_reload();
	}

	canvas_install_options();
	
	return true;
}

function canvas_install_options() {
	update_option('canvas_show_instructions','true');
	update_option('canvas_auto_reload','false');
	update_option('canvas_hide_menu','false');
	update_option('canvas_uri','http://www.freshpursuits.com/canvas/');
	update_option('canvas_allow_deletion','true');
	update_option('canvas_show_rss_tips','false');
	update_option('canvas_show_zone_name','false');
	update_option('canvas_show_shelf_tooltip','true');
	update_option('canvas_auto_publish','false');
	update_option('canvas_last_stats',time()-86500);
	update_option('canvas_share_stats','true');
	update_option('canvas_share_delay','86400');
	update_option('canvas_hide_zone_options','false');
	$filename = CANVASPATH.'/canvas.php';
	$file_data = implode('', file($filename));
	preg_match("|Version:(.*)|i", $file_data, $version);
	update_option('canvas_version',$version[1]);
	return true;
}

function canvas_reload() {
	global $wpdb, $canvas, $canvas_external_plugins;
	$current_blocks = $wpdb->get_results("SELECT block_id, path FROM ".$canvas->main." WHERE theme = '".get_option('template')."' AND type = 'block'");
	$current_plugins = $wpdb->get_results("SELECT block_id, path FROM ".$canvas->main." WHERE theme = '".get_option('template')."' AND type = 'plugin'");
	$positions = $wpdb->get_var("SELECT MAX(position) FROM ".$canvas->main." WHERE theme = '".get_option('template')."' AND zone = 'shelf'");
	if($positions) $position = $positions->position;
		else $position = 1;
	$block_count = 0; $plugin_count = 0;
	foreach($current_blocks as $block) {
		$current_block_paths[] = $block->path;
	}
	foreach($current_plugins as $plugin) {
		$current_plugin_paths[] = $plugin->path;
	}

	// Do Canvas directory
	$dir = CANVASPATH.'/blocks/';
	$files = scandirectory($dir);
	if($files) {
		foreach($files as $filename) {
			if(substr($filename, -3) == 'php') {
				$path = str_replace('\\', '/', $dir.$filename);
				if(!in_array($path, $current_block_paths)) {
					$block_data = canvas_parse_block_data($path);
					if(!empty($block_data['Name'])) {
						canvas_install_block_data($block_data,$position);
						$position++; $block_count++;
					}
				}
			}
		}
	}
	$dir = str_replace('blocks', 'plugins', $dir);
	$files = scandirectory($dir);
	if($files) {
		foreach($files as $filename) {
			if(substr($filename, -6) == 'canvas') {
				$plugin = canvas_get_plugin($dir.$filename);
				if(!in_array($plugin->functionPath, $current_plugin_paths)) {
					canvas_import_plugin($dir.$filename, $position);
					$position++; $plugin_count++;
				}
			}
		}
	}

	// Do theme directory
	$dir = TEMPLATEPATH.'/blocks/';
	$files = scandirectory($dir);
	if($files) {
		foreach($files as $filename) {
			if(substr($filename, -3) == 'php') {
				$path = str_replace('\\', '/', $dir.$filename);
				if(!in_array($path, $current_block_paths)) {
					$block_data = canvas_parse_block_data($path);
					if(!empty($block_data['Name'])) {
						canvas_install_block_data($block_data,$position);
						$position++; $block_count++;
					}
				}
			}
		}
	}
	$dir = str_replace('blocks', 'plugins', $dir);
	$files = scandirectory($dir);
	if($files) {
		foreach($files as $filename) {
			if(substr($filename, -6) == 'canvas') {
				$plugin = canvas_get_plugin($dir.$filename);
				if(!in_array($plugin->functionPath, $current_plugin_paths)) {
					canvas_import_plugin($dir.$filename, $position);
					$position++; $plugin_count++;
				}
			}
		}
	}

	// Do external plugins	
	if(!empty($canvas_external_plugins)) {
		foreach($canvas_external_plugins as $file) {
			if(file_exists($file)) {
				$plugin = canvas_get_plugin($file);
				if(!in_array($plugin->functionPath, $current_plugin_paths)) {
					canvas_import_plugin($file, $position);
					$position++; $plugin_count++;
				}
			}
		}
	}

	if($block_count > 0 || $plugin_count > 0) $message = '<p>Installed '.$block_count.' blocks and '.$plugin_count.' plugins.</p>';
		else $message = '<p>No new blocks or plugins found.</p>';

	return $message;
}

?>